<?php


namespace models\Business;

use models\Exception\Business\OrderException;
use models\Exception\Business\RefundinfoException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\RefundinfoService;
use Yaf\Registry;

class RefundInfo
{
    /**
     * 创建退货退款信息
     * @param array $parameters
     * @return array
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws RefundinfoException
     * @throws TransformerException
     */
    public static function createRefundInfo($parameters = [])
    {
        try {
            return RefundinfoService::getInstance()->create($parameters['reason'], $parameters['reason_id'], $parameters['type'], isset($parameters['album_id']) ? $parameters['album_id'] : 0, $parameters['order_sn'], 0, '','','','','', Registry::get('jwt_info')->id);
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new RefundinfoException(RefundinfoException::REFUNDINFO_CREATE_FAILURE, RefundinfoException::REFUNDINFO_CREATE_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    static public function deleteInfo($parameters = [])
    {
        try {
            $cancel_refund_return = false;
            // 判断是否是前端会员发起撤销退货退款操作
            if (isset($parameters['from_api']) && $parameters['from_api'] === true)
                $cancel_refund_return = isset($parameters['action']) && $parameters['action'] === 'cancel';

            if ($cancel_refund_return === true) {
                // 查询退货退款信息是否存在
                $refund_info = RefundinfoService::getInstance()->getOne(['groupOp' => 'AND', 'rules' => [
                    ['field' => 'order_sn', 'op' => 'eq', 'data' => $parameters['order_sn']],
                    ['field' => 'refund_order_id', 'op' => 'eq', 'data' => '0']]]);
                if (empty($refund_info))
                    throw new RefundinfoException(RefundinfoException::REFUNDINFO_IS_NOT_EXISTS, RefundinfoException::REFUNDINFO_IS_NOT_EXISTS_NO);

                // 别人的退货退款信息
                if ($refund_info['member_id'] != Registry::get('jwt_info')->id)
                    throw new RefundinfoException(RefundinfoException::REFUNDINFO_DENIED, RefundinfoException::REFUNDINFO_DENIED_NO);

                // 创建时间距离现在超过6个小时 不允许撤销
                if ($refund_info['created_at'] <= date('Y-m-d H:i:s', time() - 3600 * 6))
                    throw new RefundinfoException(RefundinfoException::REFUNDINFO_INVALID, RefundinfoException::REFUNDINFO_INVALID_NO);

                // 删除退货退款信息
                RefundinfoService::getInstance()->delete($refund_info['id']);

                // 还原booking
                Booking::editBooking(['sn' => $refund_info['order_sn'], 'stats' => 1]);

                // 还原order
                if (in_array($refund_info['type'], [1, 2]))
                    Order::editOrder(['sn' => $refund_info['order_sn'], 'stats' => $refund_info['type'], 'refund_stats' => 0]);
            }

            return new \stdClass();

        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    static public function editInfo($parameters = [])
    {
        try {
            if (!isset($parameters['id']) || empty($parameters['id']))
                throw new RefundinfoException(RefundinfoException::REFUNDINFO_IS_NOT_EXISTS, RefundinfoException::REFUNDINFO_IS_NOT_EXISTS_NO);

            $update_arr = [];
            if (isset($parameters['refund_order_id']))
                $update_arr['refund_order_id'] = $parameters['refund_order_id'];
            if (isset($parameters['logistics']))
                $update_arr['logistics'] = $parameters['logistics'];
            if (isset($parameters['reason']))
                $update_arr['reason'] = $parameters['reason'];
            if (isset($parameters['reason_id']))
                $update_arr['reason_id'] = $parameters['reason_id'];
            if (isset($parameters['album_id']))
                $update_arr['album_id'] = $parameters['album_id'];
            if (isset($parameters['type']))
                $update_arr['type'] = $parameters['type'];
            if (isset($parameters['seller_mobile']))
                $update_arr['seller_mobile'] = $parameters['seller_mobile'];
            if (isset($parameters['seller_name']))
                $update_arr['seller_name'] = $parameters['seller_name'];
            if (isset($parameters['seller_address']))
                $update_arr['seller_address'] = $parameters['seller_address'];
            if (isset($parameters['refuse']))
                $update_arr['refuse'] = $parameters['refuse'];

            if (!empty($update_arr)) {
                $info = RefundinfoService::getInstance()->update($update_arr, $parameters['id']);
            } else
                $info = RefundinfoService::getInstance()->getOne($parameters['id']);

            return $info;
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new RefundinfoException(RefundinfoException::REFUNDINFO_EDIT_FAILURE, RefundinfoException::REFUNDINFO_EDIT_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    static public function getRefundInfoByRefundSn($refund_sn) {
        try {
            return RefundinfoService::getInstance()->getOne(['groupOp' => 'AND', 'rules' => [
                ['field' => 'refund_order_id', 'op' => 'eq', 'data' => $refund_sn]
            ]]);
        } catch (\Exception $e) {
            throw new RefundinfoException(RefundinfoException::REFUNDINFO_IS_NOT_EXISTS, RefundinfoException::REFUNDINFO_IS_NOT_EXISTS_NO);
        }
    }

    /**
     * 根据订单查询退款信息
     */
    static public function getRefundInfoBySn($order_sn)
    {
        try {
            return RefundinfoService::getInstance()->getOne(['groupOp' => 'AND', 'rules' => [
                ['field' => 'order_sn', 'op' => 'eq', 'data' => $order_sn],
            ]]);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            if ($e->getCode() == ModelException::DATA_NOT_EXISTS_NO)
                throw new RefundinfoException(RefundinfoException::REFUNDINFO_IS_NOT_EXISTS, RefundinfoException::REFUNDINFO_IS_NOT_EXISTS_NO);
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     * 获取创建编辑最新退款信息
     */
    static public function getNewRefundInfo($parameters = [],$order=[])
    {
        // 判断退货退款信息是否存在，若存在则表明用户是修改已经创建好的退货退款信息；反之则表示用户需要创建退货退款信息
        $refund_is_exists = RefundInfo::getRefundInfoBySn($parameters['order_sn']);
        //退款信息存在，修改
        if (!empty($refund_is_exists)) {
            //允许修改的状态
            if(!in_array($order['refund_stats'], [1,2, 5, 6])){
                throw new OrderException(OrderException::ORDER_STATUS_OPERATE, OrderException::ORDER_STATUS_OPERATE_NO);

            }
            if($parameters['action']=='refund'){
                if($refund_is_exists['type']!=1)
                throw new OrderException(OrderException::ORDER_STATUS_OPERATE, OrderException::ORDER_STATUS_OPERATE_NO);
                $type=1;
            }else{
                if($refund_is_exists['type']!=2)
                    $type=2;
            }
            $param = [
                'id'        => $refund_is_exists['id'],
                'reason_id' => $parameters['reason_id'],
                'reason'    => $parameters['reason'],
                'type'      => $type
            ];

            // 存在图片，插入图片后将返回结果的id赋值给parameters_arr的album_id键
            if (!empty($parameters['album'])) {
                if (!empty($refund_is_exists['album_id']))
                    Album::deleteAlbum(['id' => $refund_is_exists['album_id']]);
                $param['album_id'] =self::refundAlbum($parameters['album']);
            }else{
                if (!empty($refund_is_exists['album_id']))
                    Album::deleteAlbum(['id' => $refund_is_exists['album_id']]);
                $param['album_id']=0;
            }

            if (!empty($param))
                $refundInfo = self::editInfo($param);

            return $refundInfo;

        }else{
            //退款信息不存在，创建
            //未发起退款退货才允许

            if($order['refund_stats']!=0){
                throw new OrderException(OrderException::ORDER_STATUS_OPERATE, OrderException::ORDER_STATUS_OPERATE_NO);
            }
            if ($parameters['action'] == 'refund') {
                // 判断订单状态是否为"待发货"
                if ($order['stats'] != 1) {
                    throw new OrderException(OrderException::ORDER_STATS_WAIT, OrderException::ORDER_STATS_WAIT_NO);
                }
                $parameters['type'] = 1;
            } else {
                if ($order['stats'] != 2) {
                    throw new OrderException(OrderException::ORDER_STATS_ALREADY, OrderException::ORDER_STATS_ALREADY_NO);
                }
                $parameters['type'] = 2;
            }
            if (!empty($parameters['album'])) {
                $parameters['album_id'] =self::refundAlbum($parameters['album']);
            }
            //记录退货退款信息
            $refundInfo = RefundInfo::createRefundInfo($parameters);
            return $refundInfo;
        }
    }

    /**
     * refundInfo图片上传
     */
    static public function refundAlbum($album)
    {
        $current_time = date('Y-m-d H:i:s', time());
        // 生成插入album的数组
        $album_insert_arr = ['type' => 3, 'album' => $album, 'stats' => 1, 'created_at' => $current_time, 'updated_at' => $current_time];
        // 插入数据库 并将返回结果的id赋值给parameters_arr的album_id键
        $album_res = Album::createAlbum($album_insert_arr);

        return $album_res['id'];
    }
}
